import { Workbox } from 'workbox-window';
import { envs, setCookie } from '~/utils';

if ('serviceWorker' in navigator) {
  window.addEventListener('beforeinstallprompt', (e) => {
    console.log('beforeinstallprompt');
    // 阻止自动显示安装提示
    e.preventDefault();
    // 保存事件以便稍后触发
    window.deferredPrompt = e;
  });
  window.addEventListener('appinstalled', () => {
    setCookie('isPwa', '1');
    console.log('PWA 已安装');
  });

  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/js/service-worker.js').then((registration) => {
      console.log('Service Worker registered successfully.', registration);
    }).catch((error) => {
      console.error('Service Worker registration failed:', error);
    });
  });

  // 自动注册ws代码
  // const wb = new Workbox('/sw.js');

  // wb.addEventListener('controlling', () => {
  //   window.location.reload();
  // });

  // // 合并到主线程中
  // wb.register();
}
if (envs.isPwa) {
  setCookie('isPwa', '1');
}
